package com.road2trip.datastore;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

public final class PMF {
    private static final PersistenceManagerFactory pmfInstance =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");

    private PMF() {}

    public static PersistenceManagerFactory get() {
        return pmfInstance;
    }
    
    public static PersistenceManager getPM() {
        return pmfInstance.getPersistenceManager();
    }
        
    
	protected  static Boolean makePersistent(Object o){
		 PersistenceManager pm = PMF.getPM();
		 Boolean result = true;
		 try {
			 pm.makePersistent(o);
		 }
		 catch (Exception e){
			 result = false;
		 }
		 finally{
			pm.close(); 
		 }
		 return result;
	 }
	
	
	@SuppressWarnings("unchecked")
	public static Object byID(Key id, String idKey){
		PersistenceManager pm = PMF.getPM();		 	
		Query query = pm.newQuery(Place.class);
		query.setFilter(idKey + " == " + id);
		Object result = null;
	    try {
	        List<Object> results = (List<Object>) query.execute();
	    	if (results.size() == 1) {
	    		result =  results.get(0);
	    	}
	    }catch(Exception e) {
	 	}finally {
	 		pm.close();
	 	}
	 	return result;
	 }

	
}